package top.yxqz.servlet;

import top.yxqz.school.Student;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Random;

/**
 * @author Mr.余
 * @date 2022/11/8
 * @package top.yxqz.servlet
 * ctrl+shift+R
 * Servlet默认是单列模式（单线程）
 */
public class ZhuCeServlet extends HttpServlet {
    //        存储学生们
   static ArrayList<Student> students = new ArrayList<>();
   int id = 0;

    @Override
    public void init() throws ServletException {
        System.out.println("注册功能的这个Servlet对象被实例化成功~");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context  = getServletContext();
        //        解决中文乱码问题
        String req_encoding = context.getInitParameter("req_encoding");
        String resp_encoding = context.getInitParameter("resp_encoding");
        request.setCharacterEncoding(req_encoding);
        response.setContentType(resp_encoding);

        String username = request.getParameter("username");
        String password = request.getParameter("password");
//        随机年龄
        Random random = new Random();
        int age = random.nextInt(20);
        id++;
//       1. 存储当前注册的学生
        Student student = new Student(username, id, age, password);
//       2. 存储学生们
//        students = new ArrayList<>();
        students.add(student);
        System.out.println("---------------最新注册的同学---------------");
        for (int i = 0; i < students.size(); i++) {
            Student stu = students.get(i);
            System.out.println(stu);
            PrintWriter writer = response.getWriter();
            writer.print(stu.toString());
            writer.print("<br>");
        }

//        将集合中的数据放在application作用域中
        context.setAttribute("students",students);

//        3.打印输出学生
        PrintWriter writer = response.getWriter();
        writer.print("<h1>okk</h1>");


    }
}
